import 'package:decimal/decimal.dart';
import 'package:dotted_line/dotted_line.dart';
import 'package:flutter_menu/biz/order/record/shop_car_controller.dart';
import 'package:flutter_menu/res/app_design.dart' hide PopupMenuDivider;
import 'package:flutter_menu/utils/common_utils.dart';
import 'package:get/get.dart';
import '../../../widgets/comm_dialog.dart';
import 'order_record_controller.dart';

var _mainTabHeight = 93.w;
var _columnSize = [456.w, 134.w];

_bottomBtn(String content, {void Function()? onTap}) {
  return Container(
    width: 212.w, // 固定宽度
    decoration: BoxDecoration(
        color: AppColors.bgCard,
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(_mainTabHeight / 2),
            bottomLeft: Radius.circular(_mainTabHeight / 2))),
    child: Center(
        child: Text(
      content,
      style: TextStyle(color: Colors.white, fontSize: 25.sp),
    )),
  ).onTap(onTap);
}

_dividerDotted({Color? color}) {
  return DottedLine(
    dashColor: color ?? AppColors.e2,
  );
}

_bottomWg(List<Widget> items) {
  return DefaultTextStyle(
    style: AppStyle.app_text_25.copyWith(color: AppColors.white),
    child: Container(
        height: _mainTabHeight,
        color: AppColors.bgTab,
        child: Row(
          children: items,
        )),
  );
}

_emptyWg(String content) {
  return Column(
    children: [
      Text(
        content,
        style: TextStyle(fontSize: AppDimen.sp_28, color: AppColors.text_888),
      ).center().expanded(),
      _bottomWg([
        const Spacer(),
        _bottomBtn("go_order".tr, onTap: Get.find<OrderRecordController>().continueOrder)
      ]),
    ],
  );
}

Widget _groupWidget({String name="",String count="0" ,String price="0.00",List<double>? columnSize}) {
   columnSize =columnSize?? _columnSize;
  return DefaultTextStyle(
    style: TextStyle(
      color: const Color(0xffCA7A2A),
      fontSize: AppDimen.sp_19,
      overflow: TextOverflow.ellipsis,
    ),
    child: Container(
      padding: EdgeInsets.symmetric(horizontal: 17.w),
      decoration: BoxDecoration(
        color: const Color(0xffefd976), // 背景色
        borderRadius: BorderRadius.circular(22.w), // 设置圆角
      ),
      height: 44.w,
      child: Row(
        children: [
          Text(
            name,
            maxLines: 1,
          ).size(width: columnSize[0]),
          Text(
            "shop_count".trArgs([count]),
            textAlign: TextAlign.end,
            maxLines: 1,
          ).size(width: 97.w).marginOnly(left: 16.w),
          Text(
            "shop_price".trArgs([price]),
            textAlign: TextAlign.end,
            maxLines: 1,
          ).expanded(),
        ],
      ),
    ),
  );
}

Widget _itemWidget({String name="",String count="0" ,String price="0.00",
  String specName = "",String? args, String? notice,List<double>? columnSize}) {
  columnSize =columnSize?? _columnSize;
  return  DefaultTextStyle(
    style: TextStyle(
      color: const Color(0xff652D13),
      fontSize: AppDimen.sp_24,
      overflow: TextOverflow.ellipsis,
    ),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              name,
              maxLines: 1,
            ),
            Text(
              "($specName)",
              maxLines: 1,
            ),
            if(args!=null && args.isNotEmpty)Text(
              args,
              maxLines: 1,
              style: AppStyle.app_text.copyWith(color: Color(0xffD47538)),
            ),
            if(notice!=null && notice.isNotEmpty) Text(
              notice,
              style: AppStyle.app_text.copyWith(color: Color(0xffD47538)),
              maxLines: 1,
            ),
          ],
        ).size(width: columnSize[0]),
        Text(
          count,
          maxLines: 1,
          textAlign: TextAlign.end,
        ).size(width: columnSize[1]),
        Text(
          price,
          textAlign: TextAlign.end,
          maxLines: 1,
        ).marginOnly(right: 17.w).expanded(),
      ],
    ).paddingSymmetric(vertical: 12.w),
  );
}

Widget _packageTitle(String name, String count, String price, {List<double>? columnSize}) {
  columnSize = columnSize ?? _columnSize;
  return DefaultTextStyle(
    style: TextStyle(
      color: const Color(0xff652D13),
      fontSize: AppDimen.sp_24,
      overflow: TextOverflow.ellipsis,
    ),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Text(
          name,
          maxLines: 1,
        ).size(width: columnSize[0]),
        Text(
          count,
          maxLines: 1,
          textAlign: TextAlign.end,
        ).size(width: columnSize[1]),
        Text(
          price,
          textAlign: TextAlign.end,
          maxLines: 1,
        ).marginOnly(right: 17.w).expanded(),
      ],
    ).paddingSymmetric(vertical: 12.w),
  );
}

Widget _packageContent(String name, String count, String price, String specName, String? args,
    {List<double>? columnSize}) {
  columnSize = columnSize ?? _columnSize;
  var content = DefaultTextStyle(
    style: TextStyle(
      color: const Color(0xff652D13),
      fontSize: AppDimen.sp_19,
      overflow: TextOverflow.ellipsis,
    ),
    child: Row(
      crossAxisAlignment: CrossAxisAlignment.start,
      children: [
        Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              name,
              maxLines: 1,
            ),
            Text(
              "($specName)",
              maxLines: 1,
            ),
            if (args != null && args.isNotEmpty)
              Text(
                args,
                maxLines: 1,
                style: AppStyle.app_text.copyWith(color: Color(0xffD47538)),
              ),
          ],
        ).size(width: columnSize[0]),
        Text(
          count,
          maxLines: 1,
          textAlign: TextAlign.end,
        ).size(width: columnSize[1]),
        Text(
          price,
          textAlign: TextAlign.end,
          maxLines: 1,
        ).marginOnly(right: 17.w).expanded(),
      ],
    ).paddingSymmetric(vertical: 12.w),
  );
  return content;
}


Widget _genWidgetBySku(SKU  sku){


  return Container();
}

class OrderRecordPg extends GetView<OrderRecordController>  {
  late TabController _tabController;
  @override
  Widget build(BuildContext context) {
    return GetBuilder<OrderRecordController>(
        init: controller,
        builder: (controller) {
          return DefaultTabController(
              length: tabTitles.length,
              child: Builder(builder: (ctx){
                _tabController= DefaultTabController.of(ctx);
                _tabController.addListener((){
                  controller.onTabIndexChanged(_tabController.index);
                });
                controller.tabController = _tabController;
                return body(context).whitScaffold(backgroundColor: const Color(0xffF8F6E7));
              }));
        });
  }

  Widget body(BuildContext context) {
    return SafeArea(
      child: Column(
        mainAxisSize: MainAxisSize.max,
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          _tabWg(),
          Container(
            color: AppColors.e2,
            width: double.infinity,
            height: 2.w,
          ),
          _tabContentWg(context)
        ],
      ).size(width: double.infinity),
    );
  }

  _tabWg() {
    var navColor = const Color(0xff652D13);
    return TabBar(
            controller: _tabController,
            tabs: tabTitles.map((e) {
              return Tab(
                height: 90.w,
                child: Text(
                  e,
                  style: TextStyle(fontSize: 28.sp, color: navColor),
                ),
              );
            }).toList(),
            indicatorColor: navColor,
            indicatorWeight: 2.w,
            indicatorPadding: EdgeInsets.only(bottom: 10.w, left: 30.w, right: 30.w))
        .size(width: 186.w * tabTitles.length);
  }

  _tabContentWg(BuildContext context) {
    List<Widget> widgets = [const ShopCarWidget(), _myOrderWg()];
    return TabBarView(
      controller: _tabController,
      children: widgets,
    ).expanded();
  }

  List<String> get tabTitles => ["orderTabItemOrdered".tr, "my_order".tr];

  _myOrderWg() {
    var orders = controller.myOrders;
    if (orders.isEmpty) return _emptyWg("my_order_empty".tr);
    var content = ListView.builder(
        itemCount: orders.length,
        itemBuilder: (ctx, index) {
          return _itemWidget();
        }).expanded();

    var bottom = _bottomWg([
      Spacer(),
      Text("共3项，总价: RP 1,888,000").marginOnly(right: 14.w),
      _bottomBtn("continue_order".tr, onTap: controller.continueOrder),
    ]);

    return Column(
      children: [content, bottom],
    );
  }
}

class ShopCarWidget extends GetView<ShopCarController> {
  const ShopCarWidget({super.key});

  @override
  Widget build(BuildContext context) {
    return GetBuilder<ShopCarController>(
        init: controller,
        builder: (controller) {
          return body(context);
        });
  }

  Widget body(BuildContext context) {
    if (controller.shop.isEmpty) return _emptyWg("orderTabItemOrdered_empty".tr);
    List<Widget> content = [];
    var shopItem = controller.shop;
    Decimal  allPrice  = 0.toD();
    int  allCount  = 0;
    content = shopItem.entries.expand((e){
      List<Widget> pWidgets = [];
      String groupName = e.key;
      List<ShopCarItem>  value = e.value;
      int count = 0;
      Decimal  price  = 0.toD();

      for (var item  in value ){
        price = price +   item.price.toD();
        count = count +item.count;
        SKU? sku = item.uiSKU;
        if(sku == null) continue;
        Widget child  ;

        if(sku.product.isPackage()){
          var title = _packageTitle(item.name, item.count.toString(),price.toStringAsFixed(2) );
          sku.group?.map((e){

          });
          child = Column(
            children: [title],
          );
        }else{
          child =_itemWidget(
              name: item.name,
              count: item.count.toString(),
              price: price.toStringAsFixed(2),
              specName: item.dish,
              args: item.desc,
              notice: item.notice
          );
        }

        pWidgets.addNonNull(_productWidget(context,child ,item));
        pWidgets.add(_dividerDotted());

      }
      allPrice = allPrice  +price;
      allCount = allCount  +count;
      Widget gWidget =
          _groupWidget(name: groupName, count: count.toString(), price: price.toStringAsFixed(2)).marginOnly(top: 17.w);
      return [gWidget,...pWidgets];
    }).toList();


    var bottom = _bottomWg([
      Text("continue_order".tr)
          .paddingAll(25.w)
          .onTap(controller.continueOrder)
          .marginOnly(left: 25.w),
      const Spacer(),
      Row(
        children: [
          Text("shop_count".trArgs([allCount.toString()])),
          Text("shop_price".trArgs([allPrice.toStringAsFixed(2)])),
        ],
      ).marginOnly(right: 14.w),
      _bottomBtn("confirm_order".tr, onTap: controller.onOrder),
    ]);

    return Column(
      children: [
        SingleChildScrollView(
          child: Column(
            children: content,
          ).paddingSymmetric(horizontal: 16.w ),
        ).expanded(),
        bottom
      ],
    );
  }

  Widget _productWidget(BuildContext context,Widget child,ShopCarItem model) {
    return GestureDetector(
        behavior: HitTestBehavior.opaque,
        onTapUp: (details) {
          var textS = TextStyle(fontSize: AppDimen.sp_25, color: const Color(0xff652D13));
          var bg = const Color(0xffF3EACF);
          showMenu(
            context: context,
            position: RelativeRect.fromLTRB(
              details.globalPosition.dx,
              details.globalPosition.dy,
              details.globalPosition.dx,
              details.globalPosition.dy,
            ),
            items: <PopupMenuEntry>[
              PopupMenuItem(
                child: SizedBox(
                    width: 315.w,
                    height: 57.w,
                    child: Text(
                      'edit_dishes'.tr,
                      style: textS,
                    ).center()),
                onTap: () {
                  controller.editDishes(model);
                },
              ),
              const PopupMenuDivider(),
              PopupMenuItem(
                child: SizedBox(
                    width: 315.w,
                    height: 57.w,
                    child: Text(
                      'look_img'.tr,
                      style: textS,
                    ).center()),
                onTap: () {
                  controller.lookImg(model);
                },
              ),
              const PopupMenuDivider(),
              PopupMenuItem(
                child: SizedBox(
                    width: 315.w,
                    height: 57.w,
                    child: Text(
                      'delete_dishes'.tr,
                      style: textS,
                    ).center()),
                onTap: () {
                  controller.deleteDishes(model);
                },
              ),
            ],
            color: bg,
          );
        },
        child: child);
  }
}

class PopupMenuDivider extends PopupMenuEntry<Never> {
  /// Creates a horizontal divider for a popup menu.
  ///
  /// By default, the divider has a height of 16 logical pixels.
  const PopupMenuDivider({super.key, this.height = 16});

  /// The height of the divider entry.
  ///
  /// Defaults to 16 pixels.
  @override
  final double height;

  @override
  bool represents(void value) => false;

  @override
  State<PopupMenuDivider> createState() => _PopupMenuDividerState();
}

class _PopupMenuDividerState extends State<PopupMenuDivider> {
  @override
  Widget build(BuildContext context) => Divider(
        height: widget.height,
        color: Colors.white,
      );
}

class TableChangedHintDialog extends StatelessWidget {
  GestureTapCallback? submit;
  var columnSize = [397.w, 172.w];
  List<ShopCarItem> unSupport;
  TableChangedHintDialog(this.unSupport,{super.key, this.submit});

  @override
  Widget build(BuildContext context) {
    return PopScope(
      canPop: false,
      child: Dialog(
        insetPadding: EdgeInsets.zero,
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(10.w))),
        backgroundColor: const Color(0XFFF8F6E7),
        child: DefaultTextStyle(
          style: TextStyle(color: const Color(0XFF652D13), fontSize: AppDimen.sp_21),
          child: Column(
            children: [
              Text(
                "提示",
                style: TextStyle(fontWeight: FontWeight.bold, fontSize: AppDimen.sp_30),
              ).marginOnly(top: 8.w),
              Text(
                "以下菜品未关联此房台，已为您移除",
                style: TextStyle(color: const Color(0xffFF0000), fontSize: AppDimen.sp_25),
              ).center().size(height: 60.w).marginSymmetric(horizontal: 8.w),
              _rvList().marginOnly(top: 12.w, bottom: 23.w, left: 8.w, right: 8.w).expanded(),
              Divider(
                height: 1.w,
                color: AppColors.d8d8d8,
              ),
              genBtn("确定", confirm: true, onTap: submit).marginAll(25.w),
            ],
          ).size(width: 595.w, height: 468.w),
        ),
      ),
    );
  }

  Widget _rvList() {
    return Container(
      decoration: BoxDecoration(
          border: Border.all(color: const Color(0xffA9A9A9)),
          borderRadius: BorderRadius.all(Radius.circular(8.w))),
      child: DefaultTextStyle(
        style: TextStyle(
          color: const Color(0xff652D13),
          fontSize: AppDimen.sp_24,
          overflow: TextOverflow.ellipsis,
        ),
        child: Column(
          children: [
            Row(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text("菜品").center().size(width: columnSize[0], height: 44.w),
                Text(
                  "已点",
                  maxLines: 1,
                  textAlign: TextAlign.end,
                ).center().size(width: columnSize[1], height: 44.w),
              ],
            ),
            ListView.builder(
                physics: const BouncingScrollPhysics(),
                itemCount: unSupport.length,
                itemBuilder: (ctx, index) => _item(unSupport[index])).expanded()
          ],
        ),
      ),
    );
  }

  Widget _item(ShopCarItem item) {
    return Column(
      children: [
        Row(
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Text(
                  item.name,
                  maxLines: 1,
                ),
                Text(
                  item.dish,
                  maxLines: 1,
                ),
              ],
            ).paddingOnly(left: 13.w, top: 6.w, bottom: 6.w).size(width: columnSize[0]),
            Text(
              item.count.toString(),
              maxLines: 1,
              textAlign: TextAlign.end,
            ).center().size(width: columnSize[1]),
          ],
        ),
        _dividerDotted(color: const Color(0xff979797)),
      ],
    );
  }
}
